package com.adinall.dsp.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import com.adinall.dsp.core.globle.Charset;
import com.adinall.dsp.core.utils.IOUtils;
import com.adinall.dsp.service.DownloadBean;
import com.adinall.dsp.service.FileService;

/**
 * 文件操作用Service
 * 
 * @author 高万超
 * @version V1.0.0 $ 2017年9月27日 下午5:12:47
 */
@Service
public class FileServiceImpl implements FileService {

    private Logger logger = LogManager.getLogger(getClass());

    public void download(HttpServletResponse response, DownloadBean bean) {

        InputStream is = null;
        OutputStream os = null;

        try {

            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(bean.getShowName(), Charset.UTF_8));

            os = response.getOutputStream();
            is = new FileInputStream(bean.getFilePath() + File.separator + bean.getFileName());

            byte[] buffer = new byte[2048];
            int i = -1;
            while ((i = is.read(buffer)) != -1) {
                os.write(buffer, 0, i);
            }
            os.flush();
        } catch (Exception e) {
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            IOUtils.close(is);
            IOUtils.close(os);
        }
    }
}